<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="900px"
    draggable
    @close="closeDialog"
  >
    <el-form
      v-show="props.type !== 'detail'"
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型" prop="noticeType">
            <el-select
              clearable
              style="width: 100%"
              v-model="formData.noticeType"
              placeholder="请选择类型"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('NoticeType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="组织" prop="organizationIds">
            <el-tree-select
              v-model="formData.organizationIds"
              :data="organizationList"
              :multiple="true"
              filterable
              :props="defaultProps"
              :node-key="defaultProps.value"
              :check-strictly="true"
              :show-checkbox="true"
              check-on-click-node
              style="width: 100%"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="roleIds">
            <el-select
              clearable
              style="width: 100%"
              multiple
              v-model="formData.roleIds"
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="内容" prop="noticeContent">
            <el-input
              type="textarea"
              v-model="formData.noticeContent"
              placeholder="请输入内容"
              show-word-limit
              :rows="10"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row class="ml-[15px]">
        <el-form-item label="附件上传">
          <CommonUploadFile
            :isRead="props.isReadonly"
            :files="formData.files"
            @update-files="updateFormFiles"
          />
        </el-form-item>
      </el-row>
      <el-form-item label="备注" prop="remarks">
        <el-input
          type="textarea"
          v-model="formData.remarks"
          placeholder="请输入备注"
          show-word-limit
          :maxlength="250"
        />
      </el-form-item>
    </el-form>

    <el-descriptions
      v-show="props.type === 'detail'"
      class="margin-top w-full"
      title=""
      :column="2"
      size="large"
      border
      style="padding-bottom: 30px"
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">标题</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.title || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">类型</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ useDictionary("NoticeType", formData.noticeType) }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">组织</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          <el-tooltip :visible="organizationVisible">
            <template #content>
              <span>{{
                formData.organizations
                  .map((item) => item.organizationName)
                  .join(",")
              }}</span>
            </template>
            <div
              @mouseenter="organizationVisible = true"
              @mouseleave="organizationVisible = false"
            >
              {{ buildNames(formData.organizations, "organizationName") }}
            </div>
          </el-tooltip>
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">角色</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          <el-tooltip :visible="roleVisible">
            <template #content>
              <span>{{
                formData.roles.map((item) => item.roleName).join(",")
              }}</span>
            </template>
            <div
              @mouseenter="roleVisible = true"
              @mouseleave="roleVisible = false"
            >
              {{ buildNames(formData.roles, "roleName") }}
            </div>
          </el-tooltip>
        </div>
      </el-descriptions-item>
      <el-descriptions-item :span="2">
        <template #label>
          <div class="cell-item">内容</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.noticeContent || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item :span="2">
        <template #label>
          <div class="cell-item">附件</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          <div v-if="formData.files && formData.files.length">
            <CommonUploadFile
              :showText="false"
              :isRead="true"
              :files="formData.files"
              @update-files="updateFormFiles"
            />
          </div>
          <!--          <div v-else>无</div>-->
        </div>
      </el-descriptions-item>
      <el-descriptions-item :span="2">
        <template #label>
          <div class="cell-item">备注</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.remarks || "" }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <el-table
      v-if="props.type === 'detail'"
      :data="tableData"
      highlight-current-row
      border
    >
      <el-table-column
        label="阅读人"
        prop="readerName"
        min-width="120"
        show-overflow-tooltip
        sortable
      />
      <el-table-column
        label="阅读状态"
        prop="readStatus"
        min-width="120"
        show-overflow-tooltip
        sortable
        align="center"
      >
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.readStatus === 1"
            >已阅读</el-tag
          >
          <el-tag type="info" v-else>未阅读</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="阅读时间"
        prop="readTime"
        min-width="120"
        show-overflow-tooltip
        sortable
      />
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!type || type === 'send'"
          type="primary"
          :loading="loading"
          @click="sendNotice"
          >发 布</el-button
        >
        <el-button
          v-if="!type || type === 'edit'"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "../../../../utils/useTable";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SYSNOTICEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  type: {
    type: String,
    default: "",
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const tableData = ref([]);
const organizationVisible = ref(false);
const roleVisible = ref(false);
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  title: [
    { required: true, message: "请输入标题", trigger: "blur" },
    { max: 45, message: "不能超过45个字符", trigger: "blur" },
  ],
  noticeType: [{ required: true, message: "请选择类型", trigger: "blur" }],
  roleIds: [{ required: true, message: "请选择角色", trigger: "blur" }],
  organizationIds: [{ required: true, message: "请选择组织", trigger: "blur" }],
  noticeContent: [{ required: true, message: "请输入内容", trigger: "blur" }],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  title: "",
  noticeType: "",
  files: [],
  roleIds: [],
  roles: [],
  organizationIds: [],
  organizations: [],
  noticeContent: "",
  remarks: "",
  deleted: "",
  enabled: "",
  createTime: "",
  createdUserId: "",
  lastUpdatedUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserName: "",
  enabledStr: true,
});

watch(
  () => props.data,
  (newVal: any) => {
    if (newVal?.id) {
      const {
        id,
        version,
        title,
        noticeType,
        noticeContent,
        roleIds,
        roles,
        files,
        organizationIds,
        organizations,
        remarks,
        deleted,
        enabled,
        createTime,
        createdUserId,
        lastUpdatedUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserName,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        title,
        noticeType,
        noticeContent,
        roleIds,
        roles,
        files,
        organizationIds,
        organizations,
        remarks,
        deleted,
        enabled,
        createTime,
        createdUserId,
        lastUpdatedUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserName,
      });
      if (formData.enabled == "0") {
        formData.enabledStr = false;
      } else {
        formData.enabledStr = true;
      }
      if (props.type === "detail") getTableData();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.title = "";
  formData.noticeType = "";
  formData.roleIds = [];
  formData.roles = [];
  formData.files = [];
  formData.organizationIds = [];
  formData.organizations = [];
  formData.noticeContent = "";
  formData.remarks = "";
  formData.deleted = "";
  formData.enabled = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.lastUpdatedUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserName = "";
  tableData.value = [];
  console.log(formData);
}

const loading = ref(false);

/** 保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      if (formData.enabledStr) formData.enabled = "1";
      else formData.enabled = "0";
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/system/sysnotice/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
/** 保存提交 */
function sendNotice() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "发布";
      await request({
        url: "/system/sysnotice/send",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

const getTableData = async () => {
  const { data } = await request({
    url: "/system/sysnoticereadrecord/getList",
    method: "post",
    data: {
      noticeId: formData.id,
    },
  });
  tableData.value = data;
};

/** 查询详细表 */
async function getDatails() {
  const data = await request({
    url: "/system/sysnotice/getDetails",
    method: "post",
    data: formData,
  });
  console.log(data);
}

const roleList = ref([]);

const getRoleList = async () => {
  const { data } = await request({
    url: "/system/sysRole/listALL",
    method: "post",
    data: {},
  });
  roleList.value = data;
};
const defaultProps = {
  children: "nodes",
  label: "organizationName",
  value: "id",
};
const organizationList = ref([]);

const getOrganizationList = async () => {
  const { data } = await request({
    url: "/system/sysOrganization/getUsableTree",
    method: "post",
    data: {},
  });
  organizationList.value = data;
};
onMounted(async () => {
  if (formData.id) {
    getDatails();
  }
  getRoleList();
  getOrganizationList();
});

// const list = await getDictData("NoticeTypee");

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
// 图片处理
function updateFormFiles(val: []) {
  formData.files = val;
}

const buildNames = (data, attribute) => {
  if (!data) return;
  const map = data.map((item) => item[attribute]);
  if (map.length > 3) return map.splice(0, 3).join(",") + "...";
  else return map.join(",");
};
</script>
